package com.example.mytips.utils;


import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;

public class CursorLineContent {

    ///光标所在行的内容
    public static String getLineContent(AnActionEvent e) {
        // 获取当前项目
        Project project = e.getProject();
        if (project == null) return "";

        // 获取当前编辑器
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor == null) return "";

        // 获取光标模型
        CaretModel caretModel = editor.getCaretModel();
        // 获取文档对象
        Document document = editor.getDocument();

        // 获取光标所在行的起始和结束位置
        int lineStart = document.getLineStartOffset(caretModel.getLogicalPosition().line);
        int lineEnd = document.getLineEndOffset(caretModel.getLogicalPosition().line);

        // 获取光标所在行的文本内容
        return document.getText(new TextRange(lineStart, lineEnd));
    }

    ///光标所在行的内容：line = 1：表示光标的下一行，-1所以光标的上一行
    public static String getLineContent(AnActionEvent e, int line) {
        // 获取当前项目
        Project project = e.getProject();
        if (project == null) return "";

        // 获取当前编辑器
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor == null) return "";

        // 获取光标模型
        CaretModel caretModel = editor.getCaretModel();
        // 获取文档对象
        Document document = editor.getDocument();

        // 获取光标所在行的起始和结束位置
        int wantLine = caretModel.getLogicalPosition().line + line;
        int lineStart = document.getLineStartOffset(wantLine);
        int lineEnd = document.getLineEndOffset(wantLine);

        // 获取光标所在行的文本内容
        return document.getText(new TextRange(lineStart, lineEnd));
    }


}
